package com.geqian.web.authentication.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geqian.common.common.ResponseResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无访问权限处理器
 *
 * @author geqian
 * @date 23:57 2023/1/7
 */
@Component
public class PrivilegeGrantFailedHandler implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //处理异常
        ResponseResult<String> responseResult = ResponseResult.fail(403, "无访问权限！", null);
        setResponseBody(response, objectMapper.writeValueAsString(responseResult));
    }

    private void setResponseBody(HttpServletResponse response, String message) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
